package org.test.huoche;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyStore;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public final class HttpClientUtil {
    /**
     * 证书位置
     */
    private static final String KEYSORE = "F:/huoche/huoche.keystore";

    private HttpClientUtil(){
    }

    /**
     * 通用请求
     * 
     * @return
     * @throws Exception
     */
    public static String commonRequest(String path) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        /**
         * 加入证书
         */
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(KEYSORE);
        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpGet httRequest = new HttpGet(path);
        BufferedReader br = null;
        try {
            HttpResponse response = httpClient.execute(httRequest);
            HttpEntity entity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            throw e;
        } finally {
            httRequest.abort();
            httpClient.getConnectionManager().shutdown();
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        System.out
                .println(commonRequest("https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryMyOrderNotComplete"));
    }

}
